﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lidgren.Network;

namespace Kaleta.Network.Serialization.Types
{
    public struct DistributableString
    {
        public char[] Characters;

        public DistributableString(string value)
        {
            Characters = value.ToCharArray();
        }

        public override string ToString()
        {
            return new string(Characters);
        }
        public void Set(string value)
        {
            Characters = value.ToCharArray();
        }
        public string Get()
        {
            return ToString();
        }
    }

    public class DistributableStringSerializer : IDataTypeSerialization
    {
        public void WriteData(ref object data, ref NetBuffer sendBuffer)
        {
            try
            {
                DistributableString dString = (DistributableString)data;
                if (dString.Characters != null)
                {

                    sendBuffer.Write(dString.Characters.Length);

                    foreach (var c in dString.Characters)
                        sendBuffer.Write((byte) c);

                    
                } 
                else
                    sendBuffer.Write(0);
                
            }
            catch (InvalidCastException ex)
            {
                throw new InvalidOperationException("Type is not of type DistributableString");
            }
        }

        public object ReadData(ref NetBuffer readBuffer)
        {
            int length = readBuffer.ReadInt32();
            DistributableString dString = new DistributableString();
            dString.Characters = new char[length];

            for (int i = 0; i < length; i++)
                dString.Characters[i] = (char) readBuffer.ReadByte();

            return dString;
        }
    }
}
